Backdrop

프로그래머스 ▸ 코딩테스트 입문

중복된 문자 제거
0

문제 설명

문자열 my_string이 매개변수로 주어집니다. my_string에서 중복된 문자를 제거하고 하나의 문자만 남긴 문자열을 return하도록 solution 함수를 완성해주세요.

제한사항

  • 1 ≤ my_string ≤ 110
  • my_string은 대문자, 소문자, 공백으로 구성되어 있습니다.
  • 대문자와 소문자를 구분합니다.
  • 공백(" ")도 하나의 문자로 구분합니다.
  • 중복된 문자 중 가장 앞에 있는 문자를 남깁니다.

입출력 예

my_stringresult
"people""peol"
"We are the world""We arthwold"

입출력 예 설명

입출력 예 #1

  • "people"에서 중복된 문자 "p"와 "e"을 제거한 "peol"을 return합니다.

입출력 예 #2

  • "We are the world"에서 중복된 문자 "e", " ", "r" 들을 제거한 "We arthwold"을 return합니다.

풀이

이론

Set

Set 객체는 중복되지 않는 값들을 저장하는 자료구조예요. 또한 값들을 넣은 순서대로 저장하기 때문에, Set 객체를 순회할 때에도 넣은 순서대로 순회할 수 있어요.

const mySet1 = new Set();
 
mySet1.add(1); // Set(1) { 1 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add('some text'); // Set(3) { 1, 5, 'some text' }
const o = { a: 1, b: 2 };
mySet1.add(o);
 
mySet1.add({ a: 1, b: 2 }); // o is referencing a different object, so this is okay
 
mySet1.has(1); // true
mySet1.has(3); // false, since 3 has not been added to the set
mySet1.has(5); // true
mySet1.has(Math.sqrt(25)); // true
mySet1.has('Some Text'.toLowerCase()); // true
mySet1.has(o); // true
 
mySet1.size; // 5
 
mySet1.delete(5); // removes 5 from the set
mySet1.has(5); // false, 5 has been removed
 
mySet1.size; // 4, since we just removed one value
 
mySet1.add(5); // Set(5) { 1, 'some text', {...}, {...}, 5 } - a previously deleted item will be added as a new item, it will not retain its original position before deletion
 
console.log(mySet1); // Set(5) { 1, "some text", {…}, {…}, 5 }

코드

function solution(my_string) {
  return [...new Set(my_string)].join('');
}